//
//  SSettingViewController.m
//  carcareIOS
//
//  Created by wr on 15/8/26.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "SettingsViewController.h"
//#import "DeviceInfoViewController.h"
//#import "AboutMeViewController.h"
#import "NotifiCationViewController.h"
//#import "NotiTrajectoryViewController.h"
#import "PrivacySetViewController.h"
#import "BaseWebViewController.h"

#import "SettingMgr.h"
#import "UserHelper.h"
#import "AISystemInfo.h"

//预留广告等 类似h5的接口
#import "NetAdvertice.h"
#import "AdverticePageModel.h"
#import "AlertActionSheetMgr.h"

#define SECTION_HEIGHT (11)
#define CELLHEIGHT 45

typedef NS_ENUM(NSInteger , Cell_Type) {
    Cell_Type_UpLine = 100,//cell上侧线
    Cell_Type_BottomLine,//cell下侧线
    Cell_Type_RightImage,//cell右侧图片
    
};

@interface SettingsViewController ()

@property (nonatomic , readonly) NSArray *dataArr;

@property (nonatomic , readonly) NSArray * cancelDataArr;

@property (nonatomic , strong) UILabel * deviceLabel;

@property (nonatomic , strong) UILabel * trajectoryLabel;

//预留的列表数组
@property (nonatomic , copy) NSArray * dataH5Arr;

@end

@implementation SettingsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.refreshMgr = [RefreshMgr sharedInstance];
//    [self.refreshMgr.refreshDeviceStatus startRefreshWithTimeInterval:0];
    
    [self commitView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.refreshMgr.refreshDeviceStatus startRefreshWithTimeInterval:0];
//    [self.tableView reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
//    [self.refreshMgr.refreshDeviceStatus startRefreshWithTimeInterval:0];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [self.refreshMgr.refreshDeviceStatus stopRefresh];
}
- (NSArray *)dataArr
{
    return @[@[@"空白"],@[@[@"通知提醒"],@[@"隐私设置"],@[@"安装说明"],@[@"给个好评吧"]],@[@"空白"]];
}
- (NSArray *)cancelDataArr
{
    return @[@[@"空白"],@[@"退出"],@[@"空白"]];
}
-(void)commitView {
    
    self.title = @"系统设置";
    
    //	_dataArr = @[@[@"设备信息"],@[@"通知提醒",@"轨迹地图"],@[@"关于车挣"]];
//    _dataArr = @[@[@"设备信息"],@[@"通知提醒"],@[@"关于车挣"]];
    self.view.backgroundColor = [Theme backGroundColor];
    
    [Factory labelWithFrame:CGRectMake(0, __MAIN_HEIGHT_64 - 50, __MAIN_WIDTH, 20) font:FONT_DEFAULT_Light(14) text:[NSString stringWithFormat:@"版本号：%@",[AISystemInfo sharedInstance].version] textColor:[Theme wordGrayColor] onView:self.view textAlignment:NSTextAlignmentCenter];
    self.tableView.frame = CGRectMake(0, 0, __MAIN_WIDTH, __MAIN_HEIGHT_64);
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.scrollEnabled = YES;
    self.tableView.separatorColor = [Theme lineColor];
    [self.view bringSubviewToFront:self.tableView];
    
//    __weak __typeof(self) wself = self;
//
//
//    [ViewFactory normalButtonWithFrame:FactoryRectButtonDefault(__MAIN_HEIGHT_64 - 60) title:LOCSTRING(@"exit") inView:self.view action:^{
//        [wself logout];
//    }];
    [self loadH5Data];
}
#pragma mark - 奖励计划  车挣保险等页面
- (void)loadH5Data
{
    __weak __typeof(self) wself = self;
    
    [NetAdvertice loadAdverticesWithCode:APP_SETTING success:^(NSArray *list) {
        wself.dataH5Arr = list;
        [wself.tableView reloadData];
        
    } fail:^{
        
    }];
}
#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count + (self.dataH5Arr.count > 0 ? 1 : 0) + self.cancelDataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (section < self.dataArr.count ? [self.dataArr[section] count] : ((section == self.dataArr.count ) ?  (self.dataH5Arr.count > 0 ? self.dataH5Arr.count :0) : 1));
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (indexPath.section == 0 || indexPath.section == 2 || indexPath.section == 4 || indexPath.section == 6 ) ? ((indexPath.section == 4 && self.dataH5Arr.count == 0 ) ? 0 : SECTION_HEIGHT): ((indexPath.section == 1 && indexPath.row == 1 && (![USERINFO.deviceBindingTime isNotNil])) ? 0 : CELLHEIGHT);
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    UIView * view = [Factory viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, SECTION_HEIGHT) bgColor:[Theme backGroundColor] onView:nil];
//    return view;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell;
        switch (indexPath.section) {
        case 1:
        case 3:
        {
            NSString *identifier = @"SettingsCell";
            cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
                                              reuseIdentifier:identifier];
                UIView * upLine =[[[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell.contentView];
                upLine.tag = Cell_Type_UpLine;
                UIView * bottomLine = [[[UIView viewWithFrame:CGRectMake(0, CELLHEIGHT, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell.contentView];
                bottomLine.tag = Cell_Type_BottomLine;
                UIImageView * imageV = [Factory imageViewWithCenter:CGPointMake(__MAIN_WIDTH - 25, CELLHEIGHT/2) image:ImageNamed(@"cell_right") onView:cell.contentView];
                imageV.tag = Cell_Type_RightImage;
                
            }
//[USERINFO.deviceBindingTime isNotNil]
            cell.textLabel.text = (indexPath.section == 1 ? self.dataArr[indexPath.section][indexPath.row][0] : ((AdverticePageModel *)self.dataH5Arr[indexPath.row]).title);
            cell.textLabel.font = FONT_TABLE_TITLE;
            cell.textLabel.textColor = ((indexPath.section == 1 && indexPath.row == 1 && (![USERINFO.deviceBindingTime isNotNil])) ? [UIColor clearColor] : [Theme wordColor]);
            
            UIView * upLine = [cell viewWithTag:Cell_Type_UpLine];
            [upLine setHidden:((indexPath.section == 1 && indexPath.row == 1 && (![USERINFO.deviceBindingTime isNotNil])) ? YES : NO)];
            UIView * bottomLine = [cell viewWithTag:Cell_Type_BottomLine];
            [bottomLine setHidden:((indexPath.section == 1 && indexPath.row == 1 && (![USERINFO.deviceBindingTime isNotNil])) ? YES : NO)];
            UIImageView * rightImage = [cell viewWithTag:Cell_Type_RightImage];
            [rightImage setHidden:((indexPath.section == 1 && indexPath.row == 1 && (![USERINFO.deviceBindingTime isNotNil])) ? YES : NO)];
        }
            break;
            //空白cell
        case 0:
        case 2:
        case 4:
        case 6:
        {
            NSString * cellID = (indexPath.section == 4 ? @"noChoiceCellID" : @"noCellID");
            cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
                UIView * backView = [[[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, SECTION_HEIGHT)] resetBackgroundColor:[Theme backGroundColor]] setupOnView:cell];
                    backView.layer.borderColor = (indexPath.section == 6 ? [UIColor clearColor] : [Theme lineColor]).CGColor;
                    backView.layer.borderWidth = 0.5;
                backView.tag = 10086;
            }
            UIView * backView = [cell viewWithTag:10086];
            [backView setHeight:(indexPath.section != 4  ?  SECTION_HEIGHT : ( self.dataH5Arr.count > 0 ? SECTION_HEIGHT : 0))];
        }
            break;
        case 5:
            {
                NSString * cellID = @"cancelCellID";
                cell = [tableView dequeueReusableCellWithIdentifier:cellID];
                if (!cell) {
                    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];

                    [Factory labelWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, CELLHEIGHT) font:FONT_DEFAULT_Light(16) text:@"退出当前账号" textColor:COLOR_HEXSTRING(@"#FA6804") onView:cell textAlignment:NSTextAlignmentCenter];
                    [[[UIView viewWithFrame:CGRectMake(0, CELLHEIGHT, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell.contentView];
                }
            }
                break;
        default:
            break;
    }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([Check isVisiter]) {
        return;
    }
    switch (indexPath.section) {
        case 1:
        {
            switch (indexPath.row) {
                    
                case 0:
                    //通知提醒
                    [self.navigationController pushViewController:[[[NotifiCationViewController alloc] initWithMainViewType:TYPE_MAIN_VIEW_NORMAL] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                    
                    break;
                case 1:
                    //隐私设置
                    if([USERINFO.deviceBindingTime isNotNil])[self.navigationController pushViewController:[[[PrivacySetViewController alloc] initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE] navSetupBackItemWithIdentification:BACK_ICON_TITLE] animated:YES];
                    
                    break;
                case 2:
                    //设备信息
                    //            [self.navigationController pushViewController:[[[DeviceInfoViewController alloc] init] setupNavBack] animated:YES];
                    
                    //安装说明
                    [self goInstallDeclare];
                    
                    break;
                case 3:
                    //关于车挣
                    //            [self.navigationController pushViewController:[[[AboutMeViewController alloc]  initWithTableRefreshType:TYPE_TABLE_REFRESH_NONE] setupNavBack] animated:YES];
                    //给个好评
                    [self goStar];
                    break;
                    
                    break;
                default:
                    break;
            }

        }
            break;
        case 3:
        {
            //h5点击
            AdverticePageModel * model = self.dataH5Arr[indexPath.row];
            [[StatisticsMgr sharedInstance] addClickID:[NSString stringWithFormat:@"%@-%@",APP_SETTING,model.title] description:[NSString stringWithFormat:@"设置页面中的H5设置%@",[tableView cellForRowAtIndexPath:indexPath].description]];
            [SCREEN viewController:self pushWebViewControllerWithModel:model];

        }
            break;
            
        case 5:
        {
            //退出登录
            [self logout];
        }
            break;
        default:
            break;
    }
}
- (void)goStar {
    [CommentHelper goAppStore];
}
- (void)goInstallDeclare
{
    
    BaseWebViewController * webVC = [[[BaseWebViewController alloc]initWithURL:@"http://m.ichezheng.com/install.html"]navSetupBackItemWithIdentification:BACK_ICON];
    
    webVC.isScaleBool = NO;
    webVC.title = @"安装说明";
    [self.navigationController pushViewController:webVC animated:YES];
    
}

- (void)logout {
    
    [ALERTACTIONSHEETMGR createFromVC:self withAlertType:TYPE_ALERTVC_ACTIONSHEET withTitle:LOCSTRING(@"set_app_logout") withMessage:@"" withCanCelTitle:LOCSTRING(@"cancel") withRedBtnTitle:LOCSTRING(@"ok") withOtherBtnTitle:@"" clickIndexBlock:^(NSInteger buttonIndex) {
        if(buttonIndex == 0)
        {
            [UserHelper loginOutSuccess:nil fail:nil];
            [SCREEN clear];
            [SCREEN changeToLoginScreen];
        }
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
